import time
import requests

class XiachufangIPPool:
    def __init__(self, IPTimeOout):
        self.ip_pool = {}
        # self.ipAPI = 'http://bapi.51daili.com/getapi2?linePoolIndex=0,1&packid=2&time=11&qty=1&port=1&format=txt&usertype=17&uid=61709'
        self.ipAPI = 'http://bapi.51daili.com/getapi2?linePoolIndex=0,1&packid=2&time=11&qty=1&port=1&format=txt&dt=2&ct=1&dtc=2&usertype=17&uid=61709&accessName=zhaolele&accessPassword=B57011158DC2085BB4F44BC12FEF9E4F'
        self.max_time = IPTimeOout

    def get_ip(self, change=False):
        try:
            if len(self.ip_pool) == 0 or change:
                self.ip_pool.clear()
                newIp = self.generate_ip()
                self.ip_pool[newIp['ip']] = newIp['c_time']
                return {**newIp, **{'c':True}}

            ip = next(iter(self.ip_pool))
            ip_time = self.ip_pool[ip]
            if (time.time() - ip_time) > self.max_time-20:
                self.ip_pool.clear()
                newIp = self.generate_ip()
                self.ip_pool[newIp['ip']] = newIp['c_time']
                return {**newIp, **{'c':True}}
            else:
                return {'ip':ip, 'c':False, 'c_time':ip_time}

        except:
            return {'ip':'', 'c':True, 'c_time':time.time()}
    
    def geneProxyOption(self, changeIp=False):
        returnIp = self.get_ip(changeIp)
        if returnIp['ip']:
            currentIp = returnIp['ip']
            # 解析代理格式（假设是http://ip:port格式）
            # proxy_url = currentIp.replace('http://', '') if currentIp is not None and currentIp.startswith('http://') else ''
            proxy_url = currentIp if currentIp is not None and ':' in currentIp else ''
            proxy_options = {
                'server': f'http://{proxy_url}',
                # 如果需要用户名密码
                # 'username': 'your_username',
                # 'password': 'your_password'
                'username': 'zhaolele',
                'password': 'B57011158DC2085BB4F44BC12FEF9E4F'
            }
            ret_proxy_options = {'proxy_options': proxy_options, 'c': returnIp['c'], 'c_time': returnIp['c_time']}
        else:
            ret_proxy_options = {'proxy_options': None, 'c': returnIp['c'], 'c_time': returnIp['c_time']}

        return ret_proxy_options

    def check_proxy(self, proxy):
        try:
            res = requests.get("https://httpbin.org/ip", proxies={"http": proxy}, timeout=5)
            if res.status_code == 200:
                return True
        except:
            return False
        
        return False

    def generate_ip(self):
        try_times = 5
        for i in range(try_times):
            try:
                res = requests.get(url=self.ipAPI, timeout=1.5)
                if res.status_code == 200 and self.check_proxy(res.text):
                    ip = res.text
                    return {'ip':ip, 'c_time':time.time()}
            except:
                time.sleep(1)
        return {'ip':'', 'c_time':time.time()}